package server.demo.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import server.demo.entity.Train;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Repository
public interface TrainRepository extends JpaRepository<Train, Long> {
    Optional<Train> findByTrainNumber(String trainNumber);
    
    @Query("SELECT t FROM Train t WHERE t.startStation.id = :startStationId AND t.endStation.id = :endStationId AND t.travelDate = :travelDate AND t.status = 'ACTIVE'")
    List<Train> findAvailableTrains(@Param("startStationId") Long startStationId, 
                                   @Param("endStationId") Long endStationId, 
                                   @Param("travelDate") LocalDate travelDate);
    
    List<Train> findByTravelDateAndStatus(LocalDate travelDate, Train.TrainStatus status);
    
    boolean existsByTrainNumber(String trainNumber);
    
    // 统计方法
    long countByStatus(Train.TrainStatus status);
    
    // 查找与特定车站相关的车次记录
    @Query("SELECT t FROM Train t WHERE t.startStation.id = :startStationId OR t.endStation.id = :endStationId")
    List<Train> findByStartStationIdOrEndStationId(@Param("startStationId") Long startStationId, @Param("endStationId") Long endStationId);
}